package com.sumainfor.pc.market.service;

import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.SysUserVo;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.*;
import com.sumainfor.pc.market.feign.Zfeign.ZpcEpcFeign;
import com.sumainfor.pc.market.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.market.feign.ZuulFeign.ZuulFeign;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.awt.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 市场部经理房源定价
 */
@Service
public class DmHousingInfoService implements Serializable {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(DmHousingInfoService.class);// 日志

    @Autowired
    private DmHousingInfoMapper dmHousingInfoMapper;
    @Autowired
    private DmHousingInfoPricingMapper dmHousingInfoPricingMapper;
    @Autowired
    private SeHousingInfoPricingMapper seHousingInfoPricingMapper;
    @Autowired
    private SeHousingInfoMapper seHousingInfoMapper;
    @Autowired
    private ZzuulFeign ZzuulFeign;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private ZpcEpcFeign zpcEpcFeign;
    @Autowired
    private DmHousingConMapper dmHousingConMapper;
    @Autowired
    private SeHousingConInfoMapper seHousingConInfoMapper;
    @Autowired
    private RdEpcStyleMapper rdEpcStyleMapper;

    @Autowired
    ZuulFeign ZuulFeign;

    String UUID=null;
    /**
     /**
     *查询待定价的房源列表 已通过
     */
    public List<Map<String,Object>> getDmHousingInfoList(Map<String, Object> params){
        List<Map<String,Object>> list=dmHousingInfoMapper.getDmHousingInfoList(params);
        List<String> idList=new ArrayList<String>();//保存服务中心编号
        for (Map<String,Object> map:list) {
            if (map.get("MiId")!=null){
                idList.add(map.get("MiId").toString());
            }
        }
        System.out.println("传递到网关的:"+idList);
        if(idList.size()>0){
            params.put("midList",idList);
            Map<String,Object> zuulMap=ZzuulFeign.getHousingInfoNameFd(params);
            List<Map<String,Object>> zuulList=(List<Map<String,Object>>)zuulMap.get("MiIdList");
            System.out.println("接受到网关返回的值:"+zuulMap);
            for (Map<String, Object> map : list) {
                for (Map<String, Object> map2 : zuulList) {
                    if (MapUtils.getString(map, "MiId").equals(MapUtils.getString(map2, "dept_id"))) {
                        map.putAll(map2);
                    }
                }
            }
        }
        return list;
    }
    /**
     * 查询待定价的房源列表总数 已通过
     */
    public Integer getDmHousingInfoListCount(Map<String, Object> params){
        return dmHousingInfoMapper.getDmHousingInfoListCount(params);
    }
    /**
     * 市场部经理审核房源定价
     */
    public Integer updateDmHousingInfo(Map<String,Object> params){
        Integer result=0;
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                System.out.println("params:"+params);
                List<Map<String,Object>> list=(List<Map<String,Object>>)params.get("data");
                System.out.println("list:"+list);
                List<Map<String,Object>> lister=(List<Map<String,Object>>)params.get("dataer");
                if(params.get("ProOperaType").toString().equals("1")){//房源租赁类型 1.合租 2.整租
                    Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "HouPrId");
                        put("database", Constants.DATA_SOURCE_TCMKT);
                        put("surface", "tcmkt_housing_info_pricing");
                    }});
                    if(uuid!=null &&(!uuid.get("uuid").toString().equals(""))){
                        int number=Integer.valueOf(uuid.get("uuid").toString());
                        UUID= ComUtils.getLocalTrmSeqNum("hi",number);
                    }else{
                        UUID=ComUtils.getLocalTrmSeqNum("hi",0);
                    }
                    for (int i=0;i<list.size();i++){
                        Map<String,Object> map=(Map<String,Object>)list.get(i);
                        System.out.println("新增之前的参数:"+map);
                        if (params.get("PricingStatus")!=null) {
                            map.putAll(params);
                            map.put("PricingStatus", params.get("PricingStatus"));
                        }
                        map.put("Reviewer", ContextUtils.getUserId());//定价审核人编号
                        result=seHousingInfoMapper.updateSeHousingInfo(map);
                        if (params.get("ProOperaType").toString().equals("2") && map.get("HouConType").toString().equals("2")){

                        }else{

                            Map<String,Object> dataMap=new HashMap<String,Object>();
                            dataMap.put("HouPrId",UUID);
                            dataMap.put("by", ContextUtils.getUserId());//操作人
                            dataMap.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                            dataMap.put("fnc",
                                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                            ParamsCommon.commonInsertParms(dataMap);
                            SysUserVo user=ContextUtils.getSysUser();
                            dataMap.put("HouId",params.get("HouId"));
                            dataMap.put("HouInfoId",map.get("HouInfoId"));
                            dataMap.put("IfNew",params.get("ifNew"));//是否新增或者修改      0新增   1修改   2审核

                            if(!dataMap.get("IfNew").toString().equals("0")){
                                dataMap.put("FPricing",lister.get(i).get("UnifiedPricing"));
                            }
                            dataMap.put("TPricing",map.get("UnifiedPricing"));//房源统一定价(变化后)
                            dataMap.put("OperId",dataMap.get("insby"));//当前操作人编号
                            dataMap.put("OperName",user.getName());//当前操作人名称
                            dataMap.put("OperTime",dataMap.get("instm"));//操作时间
                            seHousingInfoPricingMapper.addSeHousingInfoPricing(dataMap);
                        }
                    }
                }else{//盈利预测为整租的情况
                    Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "HouPrId");
                        put("database", Constants.DATA_SOURCE_TCMKT);
                        put("surface", "tcmkt_housing_info_pricing");
                    }});
                    if(uuid!=null &&(!uuid.get("uuid").toString().equals(""))){
                        int number=Integer.valueOf(uuid.get("uuid").toString());
                        UUID= ComUtils.getLocalTrmSeqNum("hi",number);
                    }else{
                        UUID=ComUtils.getLocalTrmSeqNum("hi",0);
                    }
                    for (int i=0;i<list.size();i++){
                        Map<String,Object> map=(Map<String,Object>)list.get(i);
                        if (params.get("PricingStatus")!=null) {
                            map.putAll(params);
                            map.put("PricingStatus", params.get("PricingStatus"));
                        }
                        if (map.get("HouConType").toString().equals("1")) {
                            result=seHousingInfoMapper.updateSeHousingInfo(map);
                        }
                        /*if (params.get("ProOperaType").toString().equals("2") && map.get("HouConType").toString().equals("2")){

                        }else{*/

                        Map<String,Object> dataMap=new HashMap<String,Object>();
                        dataMap.put("HouPrId",UUID);
                        dataMap.put("by", ContextUtils.getUserId());//操作人
                        dataMap.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                        dataMap.put("fnc",
                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                        ParamsCommon.commonInsertParms(dataMap);
                        System.out.println("HouInfoId"+params.get("HouInfoId"));
                        SysUserVo user=ContextUtils.getSysUser();
                        dataMap.put("HouId",params.get("HouId"));
                        dataMap.put("HouInfoId",map.get("HouInfoId"));
                        dataMap.put("IfNew",params.get("ifNew"));//是否新增或者修改      0新增   1修改   2审核

                        if(!dataMap.get("IfNew").toString().equals("0")){
                            dataMap.put("FPricing",lister.get(i).get("UnifiedPricing"));
                        }
                        dataMap.put("TPricing",map.get("UnifiedPricing"));//房源统一定价(变化后)
                        dataMap.put("OperId",dataMap.get("insby"));//当前操作人编号
                        dataMap.put("OperName",user.getName());//当前操作人名称
                        dataMap.put("OperTime",dataMap.get("instm"));//操作时间
                        seHousingInfoPricingMapper.addSeHousingInfoPricing(dataMap);
                    }
//                    }
                }

                //提交审核定价房源的通过通知
                CustomMap data = CustomMap.create("MeType", 4)
                        .put("Title", "提交审核定价房源的通过")
                        .put("Content", HtmlUtil.stringToHTML(String.format("恭喜！房源（%s）的定价已通过审核；",params.get("HouId")), params.get("HouId").toString(), Color.blue))
                        .put("by", ContextUtils.getUserId())
                        .put("IfJump", 1)
                        .put("Neturl", "sys-ServiceManager/serpricing")
                        .put("term", 2);
                ZuulFeign.AddMessage(data);

            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     *查询待定价的房源列表 待审核
     */
    public List<Map<String,Object>> getDmHousingInfoListw(Map<String, Object> params){
        List<Map<String,Object>> list=dmHousingInfoMapper.getDmHousingInfoListw(params);
        System.out.println("list:"+list);
        List<String> idList=new ArrayList<String>();//保存服务中心编号
        List<String> uidList=new ArrayList<String>();//保存房源定价人编号
        for (Map<String,Object> map:list) {
            if (map.get("MiId")!=null){
                idList.add(map.get("MiId").toString());
            }
            if(map.get("Founder")!=null){
                uidList.add(map.get("Founder").toString());
            }
        }

        if(idList.size()>0){
            params.put("midList",idList);
            if(uidList.size()>0){
                params.put("uidList",uidList);
            }
            System.out.println("传递到网关的:"+params);
            Map<String,Object> zuulMap=ZzuulFeign.getHousingInfoNameFd(params);
            List<Map<String,Object>> zuulList=(List<Map<String,Object>>)zuulMap.get("MiIdList");
            System.out.println("接受到网关返回的值:"+zuulMap);
            for (Map<String, Object> map : list) {
                for (Map<String, Object> map2 : zuulList) {
                    if (MapUtils.getString(map, "MiId").equals(MapUtils.getString(map2, "dept_id"))) {
                        map.putAll(map2);
                    }
                }
            }
            List<Map<String,Object>> ulList=(List<Map<String,Object>>)zuulMap.get("UiIdList");
            System.out.println("接受到网关返回的值:"+ulList);
            if (uidList!=null && uidList.size()>0) {
                for (Map<String, Object> map : list) {
                    if (map.get("Founder")!=null){
                        for (Map<String, Object> map2 : ulList) {
                            if (map.get("user_id")!=null) {
                                if (MapUtils.getString(map, "Founder").equals(MapUtils.getString(map2, "user_id"))) {
                                    map.putAll(map2);
                                }
                            }
                        }
                    }

                }
            }
        }
        return list;
    }
    /**
     * 查询待定价的房源列表总数 待审核
     */
    public Integer getDmHousingInfoListwCount(Map<String, Object> params){
        return dmHousingInfoMapper.getDmHousingInfoListwCount(params);
    }
    /**
     * 查询已通过的房源配置列表
     */
    public JsonResult getDmHousingInfoListByHouId(Map<String,Object> params) {
        JsonResult result = new JsonResult();
        if (params.get("HouId") == null) {
            return result.putFailed("参数不正确");
        }
        List<Map<String, Object>> list = dmHousingInfoMapper.getDmHousingInfoListByHouId(params);
        //查询房源特色
        List<Map<String, Object>> sryleList = rdEpcStyleMapper.getRdEpcStyleList();
        System.out.println("市场部:" + list);
        JsonResult zepcResult = zpcEpcFeign.getHoRdHpiList(params);
        System.out.println("工程部:" + zepcResult);
        if (zepcResult.get("errorCode").toString().equals("0")) {
            List<Map<String, Object>> zepcList = (List<Map<String, Object>>) zepcResult.get("result");
            for (Map<String, Object> map1 : list) {
                if (map1.get("HouConId") != null) {
                    for (Map<String, Object> map2 : zepcList) {
                        if (map2.get("HouConId") != null) {
                            if (map1.get("HouConId").toString().equals(map2.get("HouConId").toString())) {
                                map1.putAll(map2);
                            }
                        }
                    }
                }
            }
            //匹配房源特色
            for (Map<String, Object> map1 : list) {
                String StyleIdName = "";
                if (map1.get("StyleId") != null) {
                    for (Map<String, Object> map2 : sryleList) {
                        if (map2.get("Id") != null) {
                            if (map1.get("StyleId").toString().contains(map2.get("Id").toString())) {
                                StyleIdName += map2.get("Name") + ",";
                            }
                        }
                    }
                }
                map1.put("StyleIdName", StyleIdName);
            }
        }
        if (list != null) {
            result.put(list);
        } else {
            result.putFailed("服务器繁忙");
        }
        return result;
    }
}

